import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { FilterOperate, FilterOperateEntry } from '@shared/itcore/itcore.model';
import { itcoreService } from '@shared/itcore/services/itcore.service';
@Component({
    selector: 'app-itcore-db-column-fliter',
    template: `
  <div>
   
        <div *ngIf='isSelectDate ; else falseTemplate'>
            <div nz-row>
                <div nz-col nzSpan="12">  
                    <nz-select [(ngModel)]="mustDateData.column" nzAllowClear nzPlaceHolder="请选择时间字段" (ngModelChange)="dateFieldChange($event)"  style='width: 180px;'>
                            <nz-option *ngFor="let column of dateColumnList" [nzValue]="column.ColunmName" [nzLabel]="column.ColunmName"></nz-option>
                    </nz-select>
                </div>
                <div nz-col nzSpan="12">
                        <nz-input-number
                        [(ngModel)]="mustDateData.value"
                        [nzMin]="1"
                        [nzMax]="500"
                        [nzStep]="1"
                        nzSize="default"
                        nzPlaceHolder=""
                        (ngModelChange)="dateFieldChange($event)"
                        style='width: 100px;'
                        ></nz-input-number> 天
                </div>
            </div>
        
            <!-- <div nz-row>
                    <div nz-col nzSpan="24" style='text-align: right;margin-top: 30px;'>
                        <button nz-button nzType="primary" (click)='submit()'>确定</button>
                        <button nz-button  (click)='cancel()'>取消</button>
                    </div>
            </div> -->
       </div>
       <ng-template #falseTemplate>
            <!-- 选择其他多个条件 -->
            <button nz-button nzType="default" (click)='addOrtherFilter()'><i nz-icon nzType="plus-circle" nzTheme="outline" ></i>新增过滤条件</button>
            <div  *ngFor="let filter of filterGroup;let idx = index " class='boxies'>
                    <div class='box'>
                        <nz-select [(ngModel)]="filter.column" nzAllowClear nzPlaceHolder="请选择需要过滤的列字段"  style='width: 180px;'  (ngModelChange)="fieldChange($event,filter)">
                                <nz-option *ngFor="let column of columnList" [nzValue]="column.ColunmName" [nzLabel]="column.ColunmName"></nz-option>
                        </nz-select>
                   </div>
                   
                   <div class='box'  >
                        <nz-select [(ngModel)]="filter.logicOperation" nzAllowClear nzPlaceHolder="请选择逻辑运算"  style='width: 180px;'>
                                <nz-option *ngFor="let o of filter.logicOperationList" [nzValue]="o.Operate" [nzLabel]="o.Display"></nz-option>
                        </nz-select>
                   </div>
                 
                   <div class='box' >
                        <div class="f-left">
                                <!--布尔类型-->
                                <ng-container *ngIf="filter.columnType=='boolean'; else NotBoolean">
                                    <nz-select [(ngModel)]="filter.value"  [nzDisabled]="filter.logicOperation==0" (ngModelChange)="valueChange($event)">
                                        <nz-option nzValue="true" nzLabel="是"></nz-option>
                                        <nz-option nzValue="false" nzLabel="否"></nz-option>
                                    </nz-select>
                                </ng-container>
                                <ng-template #NotBoolean>
                                    <!--数值类型-->
                                    <ng-container *ngIf="filter.columnType=='int'; else NotNumber">
                                    <input nz-input [(ngModel)]="filter.value" type='number' placeholder='请输入值' (ngModelChange)="valueChange($event)" [disabled]="filter.logicOperation==0"/>
                                    </ng-container>
                                    <ng-template #NotNumber>
                                    <!--时间类型-->
                                    <ng-container *ngIf="filter.columnType=='datetime'; else NotDateTime">
                                        <nz-date-picker  [(ngModel)]="filter.value" nzFormat="yyyy-MM-dd" nzPlaceHolder="选择时间" 
                                         [nzDisabled]="!filter.logicOperation||filter.logicOperation==0" (ngModelChange)="valueChange($event)">
                                        </nz-date-picker>
                                    </ng-container>
                                    <ng-template #NotDateTime>
                                        <!--其他类型，使用字符串-->
                                        <input nz-input [(ngModel)]="filter.value" placeholder='请输入值' [disabled]="filter.logicOperation==0" (ngModelChange)="valueChange($event)"/>
                                    </ng-template>
                                    </ng-template>
                                </ng-template>
                        </div>
                   </div>
                   <div class='box' *ngIf='idx>0' >
                        <nz-select [(ngModel)]="filter.operate"  nzPlaceHolder="请选择与前一个条件的逻辑关系"  style='width: 100px;' (ngModelChange)="valueChange($event)">
                                <nz-option *ngFor="let o of filter.OperateList" [nzValue]="o.Operate" [nzLabel]="o.Display"></nz-option>
                        </nz-select>
                   </div>
                   <div class='box' style='line-height: 30px;' *ngIf='idx>0||(filterGroup.length===1)'>
                          <button nz-button (click)="removeFilter(idx)" nzType="default" nzSize="small" nzShape="circle" class="f-left">
                           <i nz-icon nzType="close" nzTheme="outline"></i>
                        </button>
                   </div>
            </div>
            <!-- <div nz-row *ngIf='filterGroup.length>0'>
                    <div nz-col nzSpan="24" style='text-align: right;padding: 30px 20% 0 0'>
                        <button nz-button nzType="primary" (click)='submitDefault()'>确定</button>
                    </div>
            </div> -->
       </ng-template>
  
  </div>
  `,
    styles: [
        `
        .boxies{
            margin-top:20px;
            display:flex;
            justify-content: left;
        }
        .box{
            margin-left:20px;
        }
        `
    ]
})
export class ItcoreDbColumnFilterComponent {
    constructor(private itcore: itcoreService, private cdf: ChangeDetectorRef) {
    }
    // 传出的成功回调
    @Output() submitSuccess = new EventEmitter<any>();

    // 取消回调
    @Output() cancelSuccess = new EventEmitter<any>();

    // 类型 是否为选择时间，
    @Input() isSelectDate: boolean;
    // 
    // 列 接口配置
    @Input() connectOption: any;

    // 编辑的值
    @Input() value: any;

    // must
    mustDateData = {
        column: '',
        value: 3
    };

    // 所有列
    columnList = [];
    dateColumnList = [];
    // 过滤组
    filterGroup = [];

    // operate
    filterOperate = [{ value: 1, text: '大于' }];

    // 获取当前表的所有列
    getColumns(callback?) {
        this.itcore.http.post('api/Db/Db/GetAllColumn', this.connectOption).subscribe(res => {
            if (res.Type === 200) {
                this.columnList = res.Data;
                this.dateColumnList = this.columnList.filter(x => x.DataType === 'datetime');
                if (callback) { callback(); }
            } else {
                this.itcore.msgSrv.error('请求列失败，请稍后重试~');
            }
        });
    }

    dateFieldChange(e) {
        this.submitSuccess.emit(this.mustDateData);
    }

    submit() {
        if (!this.mustDateData.column) {
            this.itcore.msgSrv.error('列不能为空！');
            return;
        }
        this.submitSuccess.emit(this.mustDateData);
    }
    cancel(field, data) {
        this.cancelSuccess.emit();
    }

    getOperateEntries(operates: FilterOperate[]): FilterOperateEntry[] {
        const entries: FilterOperateEntry[] = [];
        for (const operate of operates) {
            entries.push(new FilterOperateEntry(operate));
        }
        return entries;
    }
    addOrtherFilter() {
        let operateList = [];
        if (this.filterGroup && this.filterGroup.length > 0) {
            operateList = this.getOperateEntries([FilterOperate.And, FilterOperate.Or]);
        }
        const data = {
            column: '',
            columnType: '',
            value: '',
            OperateList: operateList,
            logicOperationList: [],
            logicOperation: 0,
            operate: 1
        };
        this.filterGroup.push(data);

    }
    fieldChange(field, data) {
        if (this.columnList.length === 0 || !field) {
            return;
        }
        const column = this.columnList.find(x => x.ColunmName === field);
        if (!column) {
            return;
        }
        data.columnType = column.DataType;
        data.value = '';
        data.logicOperation = 0;
        data.operate = 0;
        this.setLogicOperation(column.DataType, data);
    }
    setLogicOperation(type, data) {
        switch (type) {
            case 'int':
            case 'smallint':
                data.logicOperationList = this.getOperateEntries([FilterOperate.Equal, FilterOperate.NotEqual, FilterOperate.Less, FilterOperate.LessOrEqual, FilterOperate.Greater, FilterOperate.GreaterOrEqual]);
                break;
            case 'datetime':
                data.logicOperationList = this.getOperateEntries([FilterOperate.Equal, FilterOperate.NotEqual, FilterOperate.Less, FilterOperate.LessOrEqual, FilterOperate.Greater, FilterOperate.GreaterOrEqual]);
                break;
            default:
                data.logicOperationList = this.getOperateEntries([FilterOperate.Equal, FilterOperate.NotEqual, FilterOperate.StartsWith, FilterOperate.EndsWith, FilterOperate.Contains, FilterOperate.NotContains]);
                break;
        }
    }
    valueChange(value) {
        try {
            this.filterGroup.forEach(x => {
                if (!x.column || !x.value || x.logicOperation === 0) {
                    throw new Error('请将值填写完整！');
                }
            });
        } catch (e) {
            // this.itcore.error(e);
            return;
        }
        const resList = this.filterGroup.map(x => {
            return { column: x.column, logicOperation: x.logicOperation, value: x.value, operate: x.operate };
        });

        this.submitSuccess.emit(resList);
    }
    submitDefault() {
        try {
            this.filterGroup.forEach(x => {
                if (!x.column || !x.value || x.logicOperation === 0) {
                    throw new Error('请将值填写完整！');
                }
            });
        } catch (e) {
            this.itcore.error(e);
            return;
        }
        const resList = this.filterGroup.map(x => {
            return { column: x.column, logicOperation: x.logicOperation, value: x.value, operate: x.operate };
        });
        this.submitSuccess.emit(resList);
    }
    removeFilter(index) {
        this.filterGroup.splice(index, 1);
        this.valueChange('');
    }

    // 重置配置状态
    reset(valueOption) {
        if (!valueOption) {
            return;
        }
        const cType = Object.prototype.toString.call(valueOption);
        if (cType === '[object Array]') {
            return;
        }


        if (!valueOption.hasOwnProperty('ConnectId')) {
            return;
        }

        this.connectOption = valueOption;
        if (this.value) {

            this.getColumns(() => {
                this.setDefaultFilter();
            });
        } else {
            this.filterGroup = [];
            this.mustDateData.column = '';
            this.getColumns();
        }
    }
    // 设置默认值
    setDefaultFilter() {

        if (this.isSelectDate) {
            this.mustDateData.value = this.value.value;
            this.mustDateData.column = this.value.column;
            return;
        }
        this.value.forEach(val => {

            let operateList = [];
            if (this.filterGroup && this.filterGroup.length > 0) {
                operateList = this.getOperateEntries([FilterOperate.And, FilterOperate.Or]);
            }
            const data = {
                column: val.column,
                columnType: '',
                value: val.value,
                OperateList: operateList,
                logicOperationList: [],
                logicOperation: val.logicOperation,
                operate: val.operate
            };
            const column = this.columnList.find(x => x.ColunmName === val.column);

            this.setLogicOperation(column.DataType, data);

            this.filterGroup.push(data);
        });

    }
}
